<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>愉悦</title>
    <link rel="stylesheet" href="../common/style/reset.css" />
    <style>


      html,
      body{
        border-radius: 3px;
      }

      .view{
        width: 100%;
        height: 100%;
        background-color: #000;
        position: relative;
        
      }

      .video-view{
        position: relative;
        width: 100%;
        height: 100%;
      }

      .video-box{
        position: absolute;
        left: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
        display: flex;
        justify-content: center;
        transition: top 0.5s;
      }

      .video-box img{
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      video{
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        height: 100%;
        opacity: 1;
      }

      .function-box{
        position: fixed;
        bottom: -35px;
        left: 0;
        width: 100%;
        height: 35px;
        display: flex;
        align-items: center;
        justify-content: right;
        padding: 0 10px;
        font-size: 14px;
        color: #d1cece;
        transition: bottom 0.5s;
      }

      .function-box .btn-box{
        position: relative;
        margin-left: 10px;
      }

      .icon-sound,
      .icon-mute{
        font-size: 14px;
      }

      .icon-sound{
        display: none;
      }
      
      .icon-transparent{
        font-size: 12px;
      }


      .transparent-box{
        position: fixed;
        width: 75%;
        bottom: 30px;
        right: 0;
        left: 0;
        margin: auto;
      }

      body:hover .function-box{
        bottom: 0;
      }

      .icon-play-box{
        position: fixed;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        margin: auto;
        width: 15vw;
        height: 15vw;
        font-size: 15vmin;
      }

      icon-svg[name="play"],
      icon-svg[name="pause"]{
        opacity: 0;
        position: absolute;
        left: 0;
        top: 0;
        transition: all 0.5s;
        color: #fff;
      }

      .icon-refresh.alternate{
        animation-name: alternate;
        animation-duration: 1s;
        animation-iteration-count: infinite;
        animation-timing-function: linear;
      }

      @keyframes alternate {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }
    </style>
  </head>
  <body>
   
    <div class="view">
      <div class="video-view"></div>
      <div class="icon-play-box">
        <icon-svg name="play"></icon-svg>
        <icon-svg name="pause"></icon-svg>
      </div>
    </div>
    <div class="function-box">
      <div class="btn-box">
        <icon-svg name="refresh" title="刷新" class="icon-refresh"></icon-svg>
      </div>
      <!-- <div class="btn-box">
        <icon-svg name="hidden" class="icon-hidden"></icon-svg>
        <icon-svg name="visible" class="icon-visible"></icon-svg>
      </div> -->
      <div class="btn-box">
        <icon-svg name="lightning" class="icon-lightning"></icon-svg>
      </div>
      <div class="btn-box">
        <icon-svg name="transparent" title="透明度" class="icon-transparent"></icon-svg>
        <div class="transparent-box" style="display:none;"><l-slider value="100" h="6"></l-slider></div>
      </div>
      <div class="f-sound btn-box">
        <icon-svg name="sound" title="声音" class="icon-sound"></icon-svg>
        <icon-svg name="mute" title="静音" class="icon-mute"></icon-svg>
      </div>
    </div>
    
  </body>
  <script type="module" src="../common/js/setting.js"></script>
  <script type="module" src="../common/js/menu.js"></script>
  <script type="module" src="../common/js/move.js"></script>
  <script type="module" src="../common/js/counter.js"></script>
  <script type="module">
    import { debounce } from '../common/utils/utils.js'
    import IconSvg from "../components/IconSvg/IconSvg.js";
    customElements.define("icon-svg", IconSvg);
    import Slider from "../components/Slider.js";
    customElements.define("l-slider", Slider);
    let data = {
      transparent: 100,
      auto: false
    };
    let num = 5;
    let currentIndex = 0;
    let list = [], urls = [], muted = true;

    const viewEl = document.querySelector('.view');
    const videoViewEl = document.querySelector('.video-view');
    const soundEl = document.querySelector('.icon-sound');
    const muteEl = document.querySelector('.icon-mute');
    const sliderEl = document.querySelector('l-slider');
    const iconTransparentEl = document.querySelector('.icon-transparent');
    const transparentBoxEl = document.querySelector('.transparent-box');
    const lightningEl = document.querySelector('.icon-lightning');
    const iconPauseEl = document.querySelector('icon-svg[name="pause"]');
    const iconPlayEl = document.querySelector('icon-svg[name="play"]');
    const iconRefreshEl = document.querySelector('.icon-refresh');
    // const canvas = document.createElement('canvas');
    // let ctx = canvas.getContext('2d');

    window.getData = ()=>data;
    if(window.ipcRenderer){
      window.ipcRenderer.on('init', (event, res) => {
        data = res || data;
        viewEl.style.opacity = data.transparent / 100;
        sliderEl.setAttribute('value', data.transparent);
        if(data.auto){
          lightningEl.style.color = 'rgb(105, 171, 112)';
           lightningEl.title = '自动播放'
        }else{
          lightningEl.style.color = '#d1cece';
          lightningEl.title = '手动播放'
        }
      }); 
    }


    const getVideoUrl = async ()=>{
      try {
        let res = await fetch('https://api.kuleu.com/api/MP4_xiaojiejie?type=json');
        let data = await res.json();
        return data.mp4_video;
      } catch (error) {
        videoViewEl.innerHTML = `<div style="color:red;">网络异常，请点击右下角刷新</div>`;
        return false;
      }
    }

    const renderVideo = async (index, src)=>{
      let url;
      if(src){
        url = src;
      }else{
       url = await getVideoUrl();
       console.log(url);
       
       if(!url)return false;
       list.push(url);
      }
      const videoBox = document.createElement('div');
      const video = document.createElement('video');
      const canvas = document.createElement('canvas');
      videoBox.className = 'video-box';
      video.src = url;
      video.muted = muted;
      video.volume = 0.4;
      videoBox.style.top = `${index * 100}%`;
      videoBox.dataset.index = index;
      videoBox.appendChild(video);
      videoBox.appendChild(canvas);
      console.log(videoBox);
      
      if(index < 0){
        videoViewEl.insertBefore(videoBox, videoViewEl.firstChild);
      }else{
        videoViewEl.appendChild(videoBox);
      }
      canvas.width = videoBox.clientWidth;
      canvas.height = videoBox.clientHeight;
      return true;
    }

    const bgAn = () => {
      let time = 0
      const fn = (s) => {
        const currentVideo = document.querySelector('video[src="' + list[currentIndex] + '"]');
        // 兄弟节点
        const currentCanvas = currentVideo?.parentElement.querySelector('canvas');
        if(!currentCanvas){
          time = s;
          requestAnimationFrame(fn);
          return;
        }
        const videoWidth = currentVideo.videoWidth;
        const videoHeight = currentVideo.videoHeight;
        let ctx = currentCanvas.getContext('2d');
        ctx.clearRect(0, 0, currentCanvas.width, currentCanvas.height);

        let scale = Math.max(currentCanvas.width / videoWidth, currentCanvas.height / videoHeight);

        // 计算绘制区域的位置与大小
        let dx = (currentCanvas.width - videoWidth * scale) / 2; // x轴偏移量
        let dy = (currentCanvas.height - videoHeight * scale) / 2; // y轴偏移量
        let dWidth = videoWidth * scale; // 绘制宽度
        let dHeight = videoHeight * scale; // 绘制高度

        ctx.filter = 'blur(10px)';
        ctx.drawImage(currentVideo, 0, 0, videoWidth, videoHeight, dx, dy, dWidth, dHeight);
        
        // if(){
        // }else{
        //   console.log('tingzhi ');
          
        // }
        // console.log(s - time);
        
        time = s;
        requestAnimationFrame(fn);
        
      }

      requestAnimationFrame(fn);
    }

    const slideRender = async (type)=>{
      let videoBoxs = document.querySelectorAll('.video-box');
      if(type === 'top'){
        currentIndex--;
      }else if(type === 'bottom'){
        currentIndex++;
      }
      videoBoxs.forEach(item=>{
        let dataindex = parseInt(item.dataset.index);
        item.querySelector('video').muted = muted;
        if(type === 'top'){
          
          item.style.top = `${(dataindex + 1) * 100}%`;
          item.dataset.index = dataindex + 1;
          if(dataindex + 1 !== 0){
            item.querySelector('video').pause();
          }
        }else if(type === 'bottom'){
          item.style.top = `${(dataindex - 1) * 100}%`;
          item.dataset.index = dataindex - 1;
          if(dataindex - 1 !== 0){
            item.querySelector('video').pause();
          }
        }


      })
      
      let currentVideo = document.querySelector('video[src="' + list[currentIndex] + '"]');
      
      if(Math.abs(videoBoxs[0].dataset.index) > num / 2){
        videoBoxs[0].remove();
        let src = list[currentIndex + 2];
        await renderVideo(parseInt(videoBoxs[num - 1].dataset.index) + 1, src);
      }
   
      if(Math.abs(videoBoxs[0].dataset.index) === 1 && currentIndex !== 1){
        videoBoxs[videoBoxs.length - 1].remove();
        await renderVideo(-2, list[currentIndex - 2]);
      }
      
      try {
        await currentVideo.play();
        iconPlayEl.style.opacity = 0;
        iconPauseEl.style.opacity = 0;

        currentVideo.onended = () => {
          if(data.auto){
            slideRender('bottom');
          }else{
            currentVideo.play();
            iconPlayEl.style.opacity = 0;
            iconPauseEl.style.opacity = 0;
          }
        }
      } catch (error) {
        console.log('error');
        slideRender('bottom');
        console.log(error);
      }
      // bgAn();
      

    }
    
    const init = async ()=>{
      iconRefreshEl.classList.add('alternate');
      currentIndex = 0;
      list = [];
      videoViewEl.innerHTML = '';
      for(let i = 0; i < num; i++){
        let bool = await renderVideo(i);
        console.log(bool);
        
        if(!bool){
          return;
        }
      }

      let currentVideo = document.querySelector('video[src="' + list[currentIndex] + '"]');
      iconRefreshEl.classList.remove('alternate');
        
      try {
        await currentVideo.play();
        iconPlayEl.style.opacity = 0;
        iconPauseEl.style.opacity = 0;

        currentVideo.onended = () => {
          currentVideo.pause();
          const urlParams = new URLSearchParams(window.location.search);
          const param1 = urlParams.get('tag');
          if(param1 !== '1'){
            if(data.auto){
              slideRender('bottom');
            }else{
              currentVideo.play();
              iconPlayEl.style.opacity = 0;
              iconPauseEl.style.opacity = 0;
            }
          }
        }
      } catch (error) {
        console.log('error');
        slideRender('bottom');
        console.log(error);
      }

     
      
    }

    init();
    bgAn();

    soundEl.onclick = (e)=>{
      e.stopPropagation();
      muted = true;
      soundEl.style.display = 'none';
      muteEl.style.display = 'flex';

      let videos = document.querySelectorAll('video');
      videos.forEach(item=>{
        item.muted = muted;
      })
    }

    muteEl.onclick = (e)=>{
      e.stopPropagation();
      muted = false;
      muteEl.style.display = 'none';
      soundEl.style.display = 'flex';
      let videos = document.querySelectorAll('video');
      videos.forEach(item=>{
        item.muted = muted;
      })
    }

    iconTransparentEl.onclick = (e)=>{
      e.stopPropagation();
      if(transparentBoxEl.style.display === 'none'){
        transparentBoxEl.style.display = 'block';
      }else{
        transparentBoxEl.style.display = 'none';
      }
    }

    lightningEl.onclick = (e)=>{
      e.stopPropagation();
      data.auto = !data.auto;
      if(data.auto){
        lightningEl.style.color = 'rgb(105, 171, 112)';
        lightningEl.title = '自动播放'
      }else{
        lightningEl.style.color = '#d1cece';
        lightningEl.title = '手动播放'
      }
      if(window.sendSaveData){
        window.sendSaveData(data);
      }
    }

    sliderEl.onchange = (e)=>{
      let value = e.detail.value;
      if(value < 1){
        value = 1;
        sliderEl.setAttribute('value', 1);
      }
      data.transparent = value;
      viewEl.style.opacity = value / 100;
      if(window.sendSaveData){
        window.sendSaveData(data);
      }
    }

    iconRefreshEl.onclick = (e)=>{
      e.stopPropagation();
      init();
    }

    let playTime;
    viewEl.onclick = window.triggerHandle(()=>{
      clearTimeout(playTime);
      let currentVideo = document.querySelector('video[src="' + list[currentIndex] + '"]');
      if(!currentVideo.paused){
        currentVideo.pause();
        iconPlayEl.style.opacity = 1;
        iconPauseEl.style.opacity = 0;
      }else{
        currentVideo.play();
        iconPlayEl.style.opacity = 0;
        iconPauseEl.style.opacity = 1;
        playTime = setTimeout(()=>{
          iconPauseEl.style.opacity = 0;
        },500);
      }
      transparentBoxEl.style.display = 'none';
    })

    document.documentElement.onmouseleave = ()=>{
      transparentBoxEl.style.display = 'none';
    }


    window.onkeydown = async (e)=>{
      if(e.keyCode === 38 && currentIndex - 1 < 0){
        return;
      }
      if(e.keyCode === 40 && currentIndex + 2 > list.length - 1){
        return;
      }
      if(e.keyCode === 38 && currentIndex - 1 >= 0){
        await slideRender('top');
      }
      if(e.keyCode === 40){
        await slideRender('bottom');
      }
    }

    window.onmousewheel = async (e)=>{
      // 上滑下滑判断
      if(e.deltaY > 0 && currentIndex + 2 > list.length - 1){
        return;
      }
      if(e.deltaY < 0 && currentIndex - 1 < 0){
        return;
      }
      if(e.deltaY > 0){
        await slideRender('bottom');
      }else{
        await slideRender('top');
      }
      e.stopPropagation();

    }

    window.onresize = ()=>{
      let canvas = document.querySelectorAll('canvas');
      canvas.forEach(item=>{
        item.width = window.innerWidth;
        item.height = window.innerHeight;
      })
    }

  </script>
</html>
